<template>
  <div class="hello">
    <PianoKeys />

    <div>
      <h1>{{ formattedChord }}</h1>
      <p>{{ jsonOfChord }}</p>
    </div>

    <ChordTable @chord="handleChord" />
  </div>
</template>

<script>
import ChordTable from "./chords/table.vue";
import PianoKeys from "./piano/keyboard.vue";

function nop() {}

export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  components: { ChordTable, PianoKeys },

  data() {
    return {
      formattedChord: "",
      jsonOfChord: "",
    };
  },

  computed: {
    the128keys() {
      return this.$store.getters["keyboard/keys"];
    },
  },

  methods: {
    chord2keys(chord) {
      nop();
      let keys = {};
      let root = this.getRootKey(chord);
      if (root == null) {
        return keys;
      }
      let steps = chord.steps;
      let velocity = 100;
      let code = root.code;
      keys[code] = velocity;
      for (var i in steps) {
        let step = steps[i];
        code = code + step;
        keys[code] = velocity;
      }
      return keys;
    },

    getRootKey(chord) {
      let all = this.the128keys;
      let root = chord.root;
      for (var i = 60; ; i++) {
        let item = all[i];
        if (item == null) {
          break;
        }
        // let str = JSON.stringify(item);
        // console.log("chord2keys : " + str);
        if (item.name == root) {
          return item;
        }
      }
      return null;
    },

    handleChord(chord) {
      this.formattedChord = this.formatChord(chord);
      this.jsonOfChord = JSON.stringify(chord);

      let keys = this.chord2keys(chord);
      this.$store.commit("keyboard/reset");
      this.$store.commit("keyboard/keyDown", keys);
    },

    formatChord(chord) {
      let p1 = chord.label;
      let p2 = chord.name;
      return p1 + " " + p2;
    },
  },
};
</script>

<style scoped>
</style>
